package com.sxy.service;

import com.sxy.mapper.UserMapper;
import com.sxy.pojo.User;
import com.sxy.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
public class UserService {
    //创建SqlSessionFactory对象
    private SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 登录方法
     *
     * @param username
     * @param password
     * @return
     */
    public User select(String username, String password) {
        //创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //创建mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //执行sql,返回user对象
        User user = mapper.select(username, password);
        //释放资源
        sqlSession.close();
        return user;
    }

    /**
     * 注册方法，首先判断用户名是否存在
     *
     * @param username
     * @return
     */
    public boolean register(String username, String password) {
        //创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //创建mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //判断用户是否存在
        User user = mapper.selectByUsername(username);
        if (user == null) {
            //用户不存在,执行sql语句
            mapper.add(username, password);
            //提交事务
            sqlSession.commit();
        }
        //释放资源
        sqlSession.close();
        return user == null;
    }
}
